//
//  JHSHomeViewController.m
//  JHSSweep
//
//  Created by YanYaxing on 2017/3/22.
//  Copyright © 2017年 JHDS. All rights reserved.
//

#import "JHSHomeViewController.h"
#import "JHSSicknessDetailController.h"
#import "JHSNetworkTool.h"
#import "JHSBannersModel.h"
#import "SDCycleScrollView.h"
#import "JHSFeatureView.h"
#import "JHSSrcLabView.h"
#import "LSPaoMaView.h"
#import "JHSUserinfoModel.h"
#import "JHSCommonWealController.h"

// 图片的个数
#define KImageCount 4
@interface JHSHomeViewController ()<SDCycleScrollViewDelegate,JHSFeatureViewDelegate>
@property (nonatomic,weak) UIImageView *bannerVI;
@property (nonatomic,weak) UIView *centerView;
@property (nonatomic,weak) UIImage *bannerI;
@property (nonatomic,weak) UIView *weatherView;
@property (nonatomic,weak) UILabel *weatherLabel;
@property (nonatomic,weak) UILabel *temperatureLabel;

@property (nonatomic,assign) BOOL ifHidden;


@end

@implementation JHSHomeViewController{
    JHSUserinfoModel *_model;
    //解档信息
    NSDictionary* dict;
//    CGFloat topY;

}





//隐藏状态栏
- (BOOL)prefersStatusBarHidden {
    return !self.ifHidden;
//    NSLog(@"-->%zd",!self.ifHidden);
//    return YES;
}

-(void)viewDidAppear:(BOOL)animated{
//    _weatherView.frame=CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,70.5 );
    
    
//    [self.view setNeedsLayout];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //解档

    [self loadModeData];
    //判断有密码并且不是第一次登入才开始加载数据,如果是第一次登入并且账号和密码都为空就直接跳转到登入页面
    if (![self judgeIsOne] && _model.user_id && _model.easymob_password) {
        
            NSLog(@"不是第一次登入");
    }else{
        NSLog(@"是第一次登入");
    }
    

    _bannerModelArr = [NSMutableArray array];
    self.view.backgroundColor=[UIColor whiteColor];
    [self loadBannerData];
    [self loadWeatherData];
    //添加新特性界面
    if ([self isAppFirstRun]) {
        //添加新特性界面,并添加到父控件身上
        [self makeGuideView];
    }else{
        _ifHidden = YES;
        [self setNeedsStatusBarAppearanceUpdate];
    }
    
    [self setupUI];

    
}
//MARK:判断是否要显示新特性界面
- (BOOL) isAppFirstRun{
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary]
                                objectForKey:@"CFBundleShortVersionString"];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSString *lastRunKey = [defaults objectForKey:@"last_run_version_key"];
    
    if (!lastRunKey) {
        [defaults setObject:currentVersion forKey:@"last_run_version_key"];
//        topY=64;
        return YES;
        //上次运行版本为空，说明程序第一次运行
        
    }
    else if (![lastRunKey isEqualToString:currentVersion])
    {
        [defaults setObject:currentVersion forKey:@"last_run_version_key"];
        return YES;
        //LAST_RUN_VERSION_KEY
        // App has been updated since last run
        //有版本号，但是和当前版本号不同，说明程序已经更新了版本
    }
    return NO;
}


//代理方法
-(void) setNavHiddle:(JHSFeatureView *)view withIsShow:(NSInteger)isShow{
    
    _ifHidden = !self.ifHidden;
    [self setNeedsStatusBarAppearanceUpdate];
    
    self.navigationController.navigationBar.hidden=NO;
    self.navigationController.navigationBar.alpha = 1;
    self.tabBarController.tabBar.alpha = 1;
//    _weatherView.frame=CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,70.5 );
    
    [self.view setNeedsLayout];
}

#pragma mark - 创建及添加新特性界面
- (void)makeGuideView {
    //0.隐藏导航条和状态栏
    self.navigationController.navigationBar.hidden = YES;
//    self.tabBarController.tabBar.hidden = NO;
    
    self.navigationController.navigationBar.alpha = 0;
    self.tabBarController.tabBar.alpha = 0;
    // 1.创建新特性界面
    JHSFeatureView *guideView = [[JHSFeatureView alloc] initWithFrame:self.view.bounds];
    guideView.delegate=self;
    
    // 2.给新特性界面传递数据
    guideView.imageNames = [self loadImageNames];
    // 3.添加新特性界面到控制器view上
    [self.view addSubview:guideView];
//    [parentView exchangeSubviewAtIndex:i withSubviewAtIndex:j]//交换两个视图的位置
//    bringSubviewToFront  sendSubviewToBack
    [self.view bringSubviewToFront:guideView];

}
#pragma mark - 加载新特性界面数据
- (NSArray *)loadImageNames {
    
    // 1.创建可变数据用来保存图片名称 // Capacity 容量
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:KImageCount];
    
    // 2.for循环拼接图片名称
    for (NSInteger i = 0; i < KImageCount; i++) {
        // 2.1 拼接图片名称
        NSString *imageName = [NSString stringWithFormat:@"common_hh%zd", i + 1];
        // 2.2 添加图片名称到可变数据中
        [arrM addObject:imageName];
    }
    // 可变数组进行不可变拷贝,变了不可变
    return arrM.copy;
}

#pragma mark - 加载UI
-(void) setupUI{
    //MARK:天气view
    UIView *weatherView = [UIView new];
    weatherView.backgroundColor=JHSMainColor;
    
    [self.view addSubview:weatherView];
    [weatherView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(0);
        make.height.offset(70.5);
    }];
    
    UIImageView *weatherIV=[UIImageView new];
    weatherIV.image=[UIImage imageNamed:@"多云有阳光"];
    [weatherView addSubview:weatherIV];
    [weatherIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.offset(36);
        make.top.offset(0);
        make.left.offset(136);
        
    }];
    
    [self.view sendSubviewToBack:weatherView];
    //温度label
    UILabel *temperatureLabel=[UILabel new];
    temperatureLabel.textColor=[UIColor whiteColor];
    temperatureLabel.font=[UIFont fontWithName:@"Times New Roman" size:16];

    [weatherView addSubview:temperatureLabel];
    [temperatureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(8);
        make.left.equalTo(weatherIV.mas_right).offset(10);
        
    }];
    
    //地区label
    UILabel *weatherLabel=[UILabel new];
    weatherLabel.text=@"天气view";
    weatherLabel.textColor=[UIColor whiteColor];
    weatherLabel.font=[UIFont fontWithName:@"Times New Roman" size:16];
    [weatherView addSubview:weatherLabel];
    [weatherLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weatherIV.mas_bottom).offset(8);
        make.left.offset(50);
    }];
    
    _weatherLabel=weatherLabel;
    _temperatureLabel=temperatureLabel;
    _weatherView=weatherView;
    
    //MARK:中心图片view
    UIView *centerView = [UIView new];
    centerView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:centerView];
    [centerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weatherView.mas_bottom);
        make.left.right.offset(0);
        make.height.offset(200);
    }];
    _centerView=centerView;
    //轮播图IV
    UIImageView *bannerIV=[[UIImageView alloc]initWithImage:nil];
    [centerView addSubview:bannerIV];
    [bannerIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.offset(0);
    }];
    _bannerVI=bannerIV;
    [self.view sendSubviewToBack:centerView];

    
    //MARK:滚动labelView
    UIView *scrLabView = [UIView new];
    [self.view addSubview:scrLabView];
    [self.view sendSubviewToBack:scrLabView];

    [scrLabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(centerView.mas_bottom);
        make.left.right.offset(0);
        make.height.offset(44.5);
    }];

    NSString* text = @"【组名：鉴黄大湿，项目名：JHS(鉴黄师)】        【组长：严雅兴，组员：陈伟、卢春晖、冯程】";
    
    LSPaoMaView* paoMaView = [[LSPaoMaView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44.5) title:text];
    [paoMaView setBackgroundColor:[UIColor whiteColor]];
    [scrLabView addSubview:paoMaView];
    
    //tag说明   1为肿瘤 4为血液科 2为心血管  3为神经科  5为骨科  6为公益

    //MARK:点击的六个按钮
    //肿瘤按钮
    UIButton *tumourBtn=[UIButton new];
    [tumourBtn setTitle:@"肿瘤" forState:UIControlStateNormal];
    tumourBtn.tag=1;
    [tumourBtn setImage:[UIImage imageNamed:@"01"] forState:UIControlStateNormal];
    [self.view addSubview:tumourBtn];
    [self.view sendSubviewToBack:tumourBtn];

    [tumourBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(scrLabView.mas_bottom);
        make.height.offset(125);
        make.left.offset(0);
        make.width.offset([UIScreen mainScreen].bounds.size.width/3);
    }];
    [tumourBtn addTarget:self action:@selector(clickedBtnWithTag:) forControlEvents:UIControlEventTouchUpInside];
    

    //血液科
    UIButton *bloodBtn=[UIButton new];
    [bloodBtn setTitle:@"血液科" forState:UIControlStateNormal];
    //    [bloodBtn setBackgroundImage:[UIImage imageNamed:@"zhongliu"] forState:UIControlStateNormal];
    [bloodBtn setImage:[UIImage imageNamed:@"02"] forState:UIControlStateNormal];
    [self.view addSubview:bloodBtn];
    [self.view sendSubviewToBack:bloodBtn];

    [bloodBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(scrLabView.mas_bottom);
        make.height.offset(125);
        make.left.equalTo(tumourBtn.mas_right);
        make.width.offset([UIScreen mainScreen].bounds.size.width/3);
    }];
    bloodBtn.tag=4;
    [bloodBtn addTarget:self action:@selector(clickedBtnWithTag:) forControlEvents:UIControlEventTouchUpInside];
    

    //心血管
    UIButton *vascellumBtn=[UIButton new];
    [vascellumBtn setTitle:@"心血管" forState:UIControlStateNormal];
    [vascellumBtn setImage:[UIImage imageNamed:@"03"] forState:UIControlStateNormal];
    [self.view addSubview:vascellumBtn];
    [self.view sendSubviewToBack:vascellumBtn];

    [vascellumBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(scrLabView.mas_bottom);
        make.height.offset(125);
        make.left.equalTo(bloodBtn.mas_right);
        make.width.offset([UIScreen mainScreen].bounds.size.width/3);
    }];
    vascellumBtn.tag=2;
    [vascellumBtn addTarget:self action:@selector(clickedBtnWithTag:) forControlEvents:UIControlEventTouchUpInside];


    //神经科
    UIButton *neurologistBtn=[UIButton new];
    [neurologistBtn setTitle:@"神经科" forState:UIControlStateNormal];
    [neurologistBtn setImage:[UIImage imageNamed:@"04"] forState:UIControlStateNormal];
    [self.view addSubview:neurologistBtn];
    [self.view sendSubviewToBack:neurologistBtn];

    [neurologistBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tumourBtn.mas_bottom);
        make.height.offset(125);
        make.left.offset(0);
        make.width.offset([UIScreen mainScreen].bounds.size.width/3);
    }];
    neurologistBtn.tag=3;
    [neurologistBtn addTarget:self action:@selector(clickedBtnWithTag:) forControlEvents:UIControlEventTouchUpInside];

    
    //骨科
    UIButton *boneBtn=[UIButton new];
    [boneBtn setTitle:@"骨科" forState:UIControlStateNormal];
    [boneBtn setImage:[UIImage imageNamed:@"05"] forState:UIControlStateNormal];
    [self.view addSubview:boneBtn];
    [self.view sendSubviewToBack:boneBtn];

    [boneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tumourBtn.mas_bottom);
        make.height.offset(125);
        make.left.equalTo(neurologistBtn.mas_right);
        make.width.offset([UIScreen mainScreen].bounds.size.width/3);
    }];
    boneBtn.tag=5;
    [boneBtn addTarget:self action:@selector(clickedBtnWithTag:) forControlEvents:UIControlEventTouchUpInside];

    
    
    //公益活动
    UIButton *commonwealBtn=[UIButton new];
    [commonwealBtn setTitle:@"公益活动" forState:UIControlStateNormal];
//    [commonwealBtn setBackgroundImage:[UIImage imageNamed:@"zhongliu"] forState:UIControlStateNormal];
    [commonwealBtn setImage:[UIImage imageNamed:@"06"] forState:UIControlStateNormal];
    [self.view addSubview:commonwealBtn];
    [self.view sendSubviewToBack:commonwealBtn];

    [commonwealBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tumourBtn.mas_bottom);
        make.height.offset(125);
        make.left.equalTo(boneBtn.mas_right);
        make.width.offset([UIScreen mainScreen].bounds.size.width/3);
    }];
    commonwealBtn.tag=6;
    [commonwealBtn addTarget:self action:@selector(clickedBtnWithTag:) forControlEvents:UIControlEventTouchUpInside];

    
}


//MARK:btn的点击事件
-(void)clickedBtnWithTag:(UIButton *)button{
    if (button.tag==6) {
        JHSCommonWealController *CommonWealController = [[JHSCommonWealController   alloc]init];
        [self.navigationController pushViewController:CommonWealController animated:YES];
        return;
    }
    
    //tag说明   1为肿瘤 4为血液科 2为心血管  3为神经科  5为骨科  6为公益
    JHSSicknessDetailController *vc=[JHSSicknessDetailController new];
    
    vc.btnTag=button.tag;
    vc.hidesBottomBarWhenPushed=YES;
    self.hidesBottomBarWhenPushed=NO;

    [self.navigationController pushViewController:vc animated:YES];
    
}



//MARK:加载轮播图model
-(void) loadBannerData{
    
    NSString *url = @"http://iosapi.itcast.cn/doctor/banners.json.php";
    NSDictionary *parameters = @{@"page_size":@10,@"page":@1};
    [JHSBannersModel bannerNetDataWithURL:url withParameters:parameters withSuccessBlock:^(id responceBoby) {
        _bannerModelArr = responceBoby;
        [self showNewBannerIV];
        
    } withFailureBlock:^(NSError *error) {
        NSLog(@"加载网络失败");
    }];
    
}

//MARK:加载天气数据
- (void)loadWeatherData{
    
    NSString *url=[NSString stringWithFormat:@"http://api.map.baidu.com/telematics/v3/weather?location=%@&output=json&ak=%@",@"深圳",
                   kBDWeather_KEY];

    [JHSWeatherModel weatherNetDataWithURL:url withParameters:nil withSuccessBlock:^(id responceBoby) {
        _weatherModel = [JHSWeatherModel yy_modelWithJSON:responceBoby];
        
        [self showNewWeatherIV];
        

    } withFailureBlock:^(NSError *error) {
        
        
    }];
    
    
}


//MARK:网络加载完重新设置轮播图
-(void) showNewBannerIV{
    JHSBannersModel *model=[JHSBannersModel yy_modelWithJSON:_bannerModelArr[0]];
    JHSBannersModel *model1=[JHSBannersModel yy_modelWithJSON:_bannerModelArr[1]];
    JHSBannersModel *model2=[JHSBannersModel yy_modelWithJSON:_bannerModelArr[2]];
    
    NSArray *imagesURLStrings=@[model.banner_img_url,model1.banner_img_url,model2.banner_img_url];
    
    // 网络加载 --- 创建带标题的图片轮播器
    SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectZero delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    
    cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    NSArray *titles = @[model.banner_title,model1.banner_title,model2.banner_title];
    cycleScrollView2.titlesGroup = titles;
    cycleScrollView2.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    [_centerView addSubview:cycleScrollView2];
    [cycleScrollView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
    
    //         --- 模拟加载延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        cycleScrollView2.imageURLStringsGroup = imagesURLStrings;
        [self.view setNeedsLayout];
        
    });
    
    
    
    [self.view setNeedsDisplay];
}


//MARK:网络加载完重新设置天气
-(void) showNewWeatherIV{
    _temperatureLabel.text = _weatherModel.temperature;
    _weatherLabel.text = [NSString stringWithFormat:@"深圳(%@) %@",_weatherModel.weather,_weatherModel.date];
    [self.view setNeedsLayout];
}

#pragma mark - ICSDrawerController方法实现
-(void)leftItemClick{
    [self.drawer open];
}
#pragma mark - 加载数据
-(void)loadModeData{
    //解档
    NSString *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    filePath = [filePath stringByAppendingPathComponent:@"userInfo.plist"];
    dict = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
//    NSLog(@"%@",filePath);
    //字典转模型
    JHSUserinfoModel *model = [JHSUserinfoModel yy_modelWithDictionary:dict];
    _model = model;
    
}
//MARK:判断是不是第一次启动
-(BOOL )judgeIsOne{
    NSUserDefaults *myUD=[NSUserDefaults standardUserDefaults];
    
    if(![myUD boolForKey:@"firstStart"])
    {
        [myUD setBool:YES forKey:@"firstStart"];
        [myUD synchronize];//同步
        // NSLog(@"是第一次启动");
        return YES;
        
    }else{
        // NSLog(@"不是第一次启动");
        return NO;
    }

}
@end
